<template>
  <div class="schedule-container" style="height: calc((100vh - 214px) / 2);">
    <!-- 日历部分 -->
    <div class="calendar-section">
      <!-- 年月选择 -->
      <div class="month-picker">
        <el-button @click="prevMonth"><i class="el-icon-arrow-left"></i></el-button>
        <el-dropdown @command="changeMonth">
          <span class="el-dropdown-link">
            {{ currentYear }}年{{ currentMonthIndex + 1 }}月<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(month, index) in months" :key="index" :command="index">
              {{ month }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button @click="nextMonth"><i class="el-icon-arrow-right"></i></el-button>
      </div>

      <!-- 星期表头 -->
      <div class="week-header">
        <span v-for="(day, index) in weekDays" :key="index">{{ day }}</span>
      </div>

      <!-- 日历日期格子 -->
      <div class="calendar-days">
        <div v-for="(week, weekIndex) in calendarDays" :key="weekIndex" class="calendar-week">
          <div v-for="(day, dayIndex) in week" :key="dayIndex" class="calendar-day" :class="{
            'is-today': isToday(day),
            'has-event': hasEvent(day),
            'is-other-month': !isCurrentMonthDay(day),
            'is-selected': isSelectedDay(day)
          }" @click="!isCurrentMonthDay(day) ? null : selectDay(day)">
            <span class="date-number">{{ day.date }}</span>
            <span v-if="hasEvent(day)" class="event-marker"></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 日程详情部分 -->
    <div class="schedule-details-section" v-if="selectedDay">
      <h2><span style="font-size: 30px;color: #2D75D7;margin-right:10px">{{ selectedDay.date }}</span> <span
          style="font-size: 15px;color: #555555;">{{ selectedDay.year + '.' + selectedDay.month }} 星期{{
            getWeekday(selectedDay) }}</span></h2>
      <div v-if="selectedDay.events && selectedDay.events.length > 0">
        <div class="schedule-event" v-for="(event, index) in selectedDay.events" :key="index">
          <div class="event-time">{{ event.startTime }} - {{ event.endTime }}</div>
          <div class="event-content">{{ event.content }}</div>
        </div>
      </div>
      <div v-else>
        <p>暂无日程</p>
      </div>
    </div>

    <div v-else class="schedule-details-section">
      <p>请选择一个日期查看日程</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentYear: new Date().getFullYear(),
      currentMonthIndex: new Date().getMonth(), // 当前月份索引（0-11）
      currentMonth: "",
      weekDays: ["日", "一", "二", "三", "四", "五", "六"],
      months: Array.from({ length: 12 }, (_, i) => `${i + 1}月`),
      calendarDays: [],
      selectedDay: null,
      // 模拟数据，实际应从后端获取
      events: [
        {
          date: { year: 2025, month: 4, date: 8 },
          startTime: "16:00",
          endTime: "18:00",
          content: "关于举办第四期“敢法讲堂”的通知",
        },
        {
          date: { year: 2025, month: 4, date: 8 },
          startTime: "17:00",
          endTime: "18:00",
          content: "常见问题答疑01",
        },
        {
          date: { year: 2025, month: 4, date: 8 },
          startTime: "17:00",
          endTime: "18:00",
          content: "常见问题答疑02",
        },
        {
          date: { year: 2025, month: 4, date: 8 },
          startTime: "17:00",
          endTime: "18:00",
          content: "常见问题答疑02",
        },
        {
          date: { year: 2025, month: 4, date: 8 },
          startTime: "17:00",
          endTime: "18:00",
          content: "常见问题答疑02",
        },
        {
          date: { year: 2025, month: 4, date: 15 },
          startTime: "14:00",
          endTime: "15:00",
          content: "项目评审会议",
        },
        {
          date: { year: 2025, month: 4, date: 20 },
          startTime: "10:00",
          endTime: "12:00",
          content: "部门周例会",
        }
      ],
    };
  },
  computed: {},
  created() {
    this.updateCalendar();
    // 默认选中当天
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonthIndex = today.getMonth();
    const date = today.getDate();

    // 构造一个类似 calendar-day 的 day 对象
    this.selectedDay = {
      date: date,
      year: currentYear,
      month: currentMonthIndex,
      events: []
    };

    // 查找当天是否有事件
    this.events.forEach(event => {
      if (
        event.date.year === currentYear &&
        event.date.month === currentMonthIndex &&
        event.date.date === date
      ) {
        this.selectedDay.events.push(event);
      }
    });
  },
  methods: {
    isSelectedDay(day) {
      return this.selectedDay && day.date === this.selectedDay.date &&
        day.month === this.selectedDay.month &&
        day.year === this.selectedDay.year;
    },
    fillPreviousMonthDays(currentDate, week) {
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth();
      const prevMonth = month === 0 ? 11 : month - 1;
      const prevYear = prevMonth === 11 ? year - 1 : year;

      const prevMonthLastDay = new Date(year, month, 0).getDate(); // 上个月最后一天
      const startDayIndex = currentDate.getDay();

      for (let i = 0; i < startDayIndex; i++) {
        const dateNum = prevMonthLastDay - (startDayIndex - i - 1);
        const dayObj = {
          date: dateNum,
          year: prevYear,
          month: prevMonth,
          events: []
        };

        // 设置上个月份的事件
        this.events.forEach(event => {
          if (
            event.date.year === prevYear &&
            event.date.month === prevMonth &&
            event.date.date === dateNum
          ) {
            dayObj.events.push(event);
          }
        });

        week.push(dayObj);
      }
    },
    updateCalendar() {
      const firstDay = new Date(this.currentYear, this.currentMonthIndex, 1);
      const lastDay = new Date(this.currentYear, this.currentMonthIndex + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startDayIndex = firstDay.getDay();

      let week = [];
      this.calendarDays = [];

      // 补充上个月的天数
      this.fillPreviousMonthDays(firstDay, week);

      // 填充本月的每一天
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(this.currentYear, this.currentMonthIndex, i);
        const dayObj = {
          date: i,
          year: date.getFullYear(),
          month: date.getMonth(),
          events: [],
        };

        // 筛选当天事件
        this.events.forEach((event) => {
          if (
            event.date.year === dayObj.year &&
            event.date.month === dayObj.month &&
            event.date.date === dayObj.date
          ) {
            dayObj.events.push(event);
          }
        });

        week.push(dayObj);

        // 每满 7 天换行
        if (week.length % 7 === 0) {
          this.calendarDays.push(week);
          week = [];
        }
      }

      // 可选：补充下个月的天数（用于占位）
      if (week.length > 0 && week.length < 7) {
        const remainingDays = 7 - week.length;
        const nextMonth = this.currentMonthIndex === 11 ? 0 : this.currentMonthIndex + 1;
        const nextYear =
          this.currentMonthIndex === 11 ? this.currentYear + 1 : this.currentYear;

        for (let i = 1; i <= remainingDays; i++) {
          const dayObj = {
            date: i,
            year: nextYear,
            month: nextMonth,
            events: []
          };

          this.events.forEach((event) => {
            if (
              event.date.year === nextYear &&
              event.date.month === nextMonth &&
              event.date.date === i
            ) {
              dayObj.events.push(event);
            }
          });

          week.push(dayObj);
        }

        this.calendarDays.push(week);
      } else if (week.length > 0) {
        this.calendarDays.push(week);
      }

      this.currentMonth = this.currentYear + "." + (this.currentMonthIndex + 1);
    },
    prevMonth() {
      if (this.currentMonthIndex === 0) {
        this.currentYear--;
        this.currentMonthIndex = 11;
      } else {
        this.currentMonthIndex--;
      }
      this.selectedDay = null;
      this.updateCalendar();
    },
    nextMonth() {
      if (this.currentMonthIndex === 11) {
        this.currentYear++;
        this.currentMonthIndex = 0;
      } else {
        this.currentMonthIndex++;
      }
      this.selectedDay = null;
      this.updateCalendar();
    },
    changeMonth(index) {
      this.currentMonthIndex = index;
      this.selectedDay = null;
      this.updateCalendar();
    },
    isToday(day) {
      const today = new Date();
      return (
        day.year === today.getFullYear() &&
        day.month === today.getMonth() &&
        day.date === today.getDate()
      );
    },
    hasEvent(day) {
      return day.events && day.events.length > 0;
    },
    selectDay(day) {
      this.selectedDay = day;
    },
    getWeekday(day) {
      const date = new Date(day.year, day.month, day.date);
      const weekday = date.getDay();
      return this.weekDays[weekday];
    },
    isCurrentMonthDay(day) {
      return day.year === this.currentYear && day.month === this.currentMonthIndex;
    }
  }
};
</script>

<style scoped>
.is-other-month .date-number {
  color: #999;
  opacity: 0.6;
}

.is-other-month:hover {
  background-color: transparent !important;
  cursor: default;
}

/* 当天样式 */
/* .is-today .date-number {
  background-color: #2D75D7;
  color: white;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
} */

/* 日程红点（左上角） */
.calendar-day .event-marker {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 6px;
  height: 6px;
  background-color: red;
  border-radius: 50%;
  z-index: 2;
}

.schedule-container {
  display: flex;
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
  padding: 10px;
  /* 原 20px 缩小 10% */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: scale(0.95);
  /* 视觉上整体缩小 5% */
  transform-origin: center center;
  overflow: hidden;
  font-size: 85%;
  /* 字体缩小 10% */
  box-sizing: border-box;
  /* 确保 padding 不影响布局 */
}

.calendar-section {
  width: 50%;
  border-right: 1px solid #ccc;
  padding-right: 20px;
}

.month-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.week-header {
  display: flex;
  justify-content: space-around;
  /* margin-bottom: 10px; */
}

.week-header span {
  text-align: center;
  flex: 1;
}

.calendar-days {
  display: flex;
  flex-wrap: wrap;
}

.calendar-week {
  display: flex;
  width: 100%;
}

.calendar-day {
  position: relative;
  width: calc(100% / 7);
  height: 42px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid transparent;
  transition: background-color 0.3s ease;
}

.calendar-day.is-selected .date-number {
  border-radius: 50%;
  background-color: #2D75D7;
  /* 继承原 is-today 背景色 */
  color: white;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
}

.calendar-day:hover .date-number:not(.is-selected .date-number) {
  border-radius: 50%;
  background-color: #f5f7fa;
  color: #333;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
  font-weight: normal;
}

/* .calendar-day:hover .event-marker,
.calendar-day.is-selected .event-marker {
  visibility: hidden; 可选：hover/selected 时隐藏红点
} */

.calendar-day .date-number {
  z-index: 1;
}

.schedule-details-section {
  width: 50%;
  padding: 0 20px;
  overflow-y: auto;
  max-height: calc(100vh - 250px); /* 根据实际情况调整 */
}

.schedule-event {
  border: 1px solid #ebeef5;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background: #F8F8F8;
}

.event-time {
  color: #999;
  font-size: 13px;
  margin-bottom: 5px;
}

.event-content {
  font-weight: 400;
  font-size: 14px;
  color: #999999;
}
</style>